// Tierless
// Copyright © 2010 Alphora
// This file is licensed under a modified BSD-license (see tierless_license.txt).
using System;
using System.Data.Common;

namespace Tierless.Infrastructure.Data
{
	/// <summary>
	/// Provides a connection wrapper that allows disposal of the connection to be determined by the caller.
	/// </summary>
	/// <remarks>
	/// This wrapper provides a disposable facade on top of connections that allows them to be wrapped
	/// using the disposable pattern without necessarily disposing them. This pattern is used in the
	/// provider to implement bring-your-own-connection semantics.
	/// </remarks>
	public class ConnectionWrapper : IDisposable
	{
		/// <summary>
		/// Constructs a new instance of the connection wrapper.
		/// </summary>
		/// <param name="connection">The connection to be wrapped.</param>
		/// <param name="shouldDispose">Whether or not the connection should be disposed when the wrapper is disposed.</param>
		public ConnectionWrapper(DbConnection connection, bool shouldDispose)
		{
			Connection = connection;
			_shouldDispose = shouldDispose;
		}

		#region IDisposable Members

		/// <summary>
		/// Disposes the connection wrapper and the underlying connection, if necessary.
		/// </summary>
		public void Dispose()
		{
			if ((Connection != null) && _shouldDispose)
			{
				Connection.Dispose();
				Connection = null;
			}
		}

		#endregion

		/// <summary>
		/// Gets the wrapped connection.
		/// </summary>
		public DbConnection Connection { get; private set; }

		private bool _shouldDispose;
	}
}
